package com.qiangesoft.im.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiangesoft.im.auth.UserUtil;
import com.qiangesoft.im.core.constant.ChatTypeEnum;
import com.qiangesoft.im.entity.*;
import com.qiangesoft.im.exception.ServiceException;
import com.qiangesoft.im.mapper.ImMessageMapper;
import com.qiangesoft.im.pojo.bo.ImChatMessageBO;
import com.qiangesoft.im.pojo.dto.ImMessageDTO;
import com.qiangesoft.im.pojo.dto.query.MessageQueryDTO;
import com.qiangesoft.im.pojo.dto.query.PageQueryDTO;
import com.qiangesoft.im.pojo.vo.ImMessageVO;
import com.qiangesoft.im.pojo.vo.PageResultVO;
import com.qiangesoft.im.pojo.vo.SysUserVo;
import com.qiangesoft.im.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 群消息 服务实现类
 * </p>
 *
 * @author qiangesoft
 * @date 2024-02-07
 */
@Service
public class ImMessageServiceImpl extends ServiceImpl<ImMessageMapper, ImMessage> implements IImMessageService {

    @Lazy
    @Autowired
    private IImChatService chatService;
    @Autowired
    private IImFriendService friendService;
    @Autowired
    private IImGroupUserService groupUserService;
    @Autowired
    private IImMessageReceiverService messageReceiverService;
    @Autowired
    private ISysUserService sysUserService;

    @Override
    public PageResultVO<ImMessageVO> listMessage(PageQueryDTO pageQuery, MessageQueryDTO messageQuery) {
        Long chatId = messageQuery.getChatId();
        ImChat chat = chatService.getById(chatId);
        if (chat == null) {
            throw new ServiceException("聊天不存在");
        }

        Long userId = UserUtil.getUserId();

        Integer pageNum = pageQuery.getPageNum();
        Integer pageSize = pageQuery.getPageSize();

        PageResultVO<ImMessageVO> pageResult = new PageResultVO<>();
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);

        IPage<ImMessageVO> messagePage = baseMapper.listMessage(new Page<>(pageNum, pageSize), userId, messageQuery.getChatId(), messageQuery.getMessageType(), messageQuery.getMessage());
        pageResult.setTotal(messagePage.getTotal());
        pageResult.setPages(messagePage.getPages());
        List<ImMessageVO> records = messagePage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            pageResult.setResults(records);
            return pageResult;
        }

        Set<Long> senderIdList = records.stream().map(ImMessageVO::getSenderId).collect(Collectors.toSet());
        Long targetId = chat.getTargetId();
        Map<Long, String> avatarMap = sysUserService.listByIds(senderIdList).stream().collect(Collectors.toMap(SysUser::getId, SysUser::getAvatar));
        Map<Long, String> nickNameMap = new HashMap<>();
        if (ChatTypeEnum.GROUP.getCode().equals(chat.getChatType())) {
            LambdaQueryWrapper<ImGroupUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ImGroupUser::getGroupId, targetId)
                    .in(ImGroupUser::getUserId, senderIdList);
            nickNameMap = groupUserService.list(queryWrapper).stream().collect(Collectors.toMap(ImGroupUser::getUserId, ImGroupUser::getNickName));
        } else {
            ImFriend friend = friendService.getById(targetId);
            nickNameMap.put(userId, UserUtil.getNickName());
            nickNameMap.put(targetId, friend.getRemark());
        }
        for (ImMessageVO record : records) {
            SysUserVo sysUserVo = new SysUserVo();
            Long senderId = record.getSenderId();
            sysUserVo.setId(senderId);
            sysUserVo.setAvatar(avatarMap.get(senderId));
            sysUserVo.setNickName(nickNameMap.get(senderId));
            record.setSender(sysUserVo);
        }
        pageResult.setResults(records);
        return pageResult;
    }

    @Override
    public List<ImMessageVO> listUnreadMessage(Long chatId) {
        ImChat chat = chatService.getById(chatId);
        if (chat == null) {
            throw new ServiceException("聊天不存在");
        }

        Long userId = UserUtil.getUserId();
        List<ImMessageVO> records = baseMapper.listUnreadMessage(userId, chatId);
        if (CollectionUtils.isEmpty(records)) {
            return records;
        }

        Set<Long> senderIdList = records.stream().map(ImMessageVO::getSenderId).collect(Collectors.toSet());
        Long targetId = chat.getTargetId();
        Map<Long, String> avatarMap = sysUserService.listByIds(senderIdList).stream().collect(Collectors.toMap(SysUser::getId, SysUser::getAvatar));
        Map<Long, String> nickNameMap = new HashMap<>();
        if (ChatTypeEnum.GROUP.getCode().equals(chat.getChatType())) {
            LambdaQueryWrapper<ImGroupUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ImGroupUser::getGroupId, targetId)
                    .in(ImGroupUser::getUserId, senderIdList);
            nickNameMap = groupUserService.list(queryWrapper).stream().collect(Collectors.toMap(ImGroupUser::getUserId, ImGroupUser::getNickName));
        } else {
            ImFriend friend = friendService.getById(targetId);
            nickNameMap.put(userId, UserUtil.getNickName());
            nickNameMap.put(targetId, friend.getRemark());
        }
        for (ImMessageVO record : records) {
            SysUserVo sysUserVo = new SysUserVo();
            Long senderId = record.getSenderId();
            sysUserVo.setId(senderId);
            sysUserVo.setAvatar(avatarMap.get(senderId));
            sysUserVo.setNickName(nickNameMap.get(senderId));
            record.setSender(sysUserVo);
        }
        return records;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ImMessage send(ImMessageDTO messageDTO) {
        Long userId = UserUtil.getUserId();

        ImMessage message = null;
        String chatType = messageDTO.getChatType();
        if (ChatTypeEnum.GROUP.getCode().equals(chatType)) {
            message = this.sendGroupMessage(messageDTO, userId);
        }
        if (ChatTypeEnum.PERSON.getCode().equals(chatType)) {
            message = this.sendPersonMessage(messageDTO, userId);
        }
        return message;
    }

    /**
     * 私聊消息
     *
     * @param messageDTO
     * @param userId
     * @return
     */
    private ImMessage sendPersonMessage(ImMessageDTO messageDTO, Long userId) {
        Long friendUserId = messageDTO.getTargetId();
        LambdaQueryWrapper<ImFriend> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ImFriend::getFriendUserId, friendUserId)
                .eq(ImFriend::getUserId, userId)
                .eq(ImFriend::getDelFlag, false);
        ImFriend friend = friendService.getOne(queryWrapper);
        if (friend == null) {
            throw new ServiceException("非好友关系");
        }

        // 聊天会话
        Long chatId = messageDTO.getChatId();
        if (chatId == null) {
            LambdaQueryWrapper<ImChat> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(ImChat::getUserId, userId)
                    .eq(ImChat::getChatType, messageDTO.getChatType())
                    .eq(ImChat::getTargetId, friendUserId)
                    .eq(ImChat::getDelFlag, false);
            ImChat chat = chatService.getOne(queryWrapper1);
            if (chat == null) {
                chat = new ImChat();
                chat.setUserId(userId);
                chat.setChatType(messageDTO.getChatType());
                chat.setTargetId(friendUserId);
                chat.setDelFlag(false);
                chatService.save(chat);
            }
            messageDTO.setChatId(chat.getId());
        }

        // 消息
        ImMessage message = new ImMessage();
        message.setSenderId(userId);
        message.setChatId(messageDTO.getChatId());
        message.setMessageType(messageDTO.getMessageType());
        message.setMessage(messageDTO.getMessage());
        message.setDelFlag(false);
        baseMapper.insert(message);

        // 发送
        ImMessageReceiver messageReceiver = new ImMessageReceiver();
        messageReceiver.setMessageId(message.getId());
        messageReceiver.setReceiverId(friendUserId);
        messageReceiver.setDelFlag(false);
        messageReceiver.setReadFlag(false);
        messageReceiverService.save(messageReceiver);
        return message;
    }

    /**
     * 群聊消息
     *
     * @param messageDTO
     * @param userId
     * @return
     */
    private ImMessage sendGroupMessage(ImMessageDTO messageDTO, Long userId) {
        Long groupId = messageDTO.getTargetId();
        LambdaQueryWrapper<ImGroupUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ImGroupUser::getGroupId, groupId)
                .eq(ImGroupUser::getUserId, userId)
                .eq(ImGroupUser::getDelFlag, false);
        ImGroupUser imGroupUser = groupUserService.getOne(queryWrapper);
        if (imGroupUser == null) {
            throw new ServiceException("无法发言，您已不在群中");
        }

        // 聊天会话
        Long chatId = messageDTO.getChatId();
        if (chatId == null) {
            LambdaQueryWrapper<ImChat> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(ImChat::getUserId, userId)
                    .eq(ImChat::getChatType, messageDTO.getChatType())
                    .eq(ImChat::getTargetId, groupId)
                    .eq(ImChat::getDelFlag, false);
            ImChat chat = chatService.getOne(queryWrapper1);
            if (chat == null) {
                chat = new ImChat();
                chat.setUserId(userId);
                chat.setChatType(messageDTO.getChatType());
                chat.setTargetId(groupId);
                chat.setDelFlag(false);
                chatService.save(chat);
            }
            messageDTO.setChatId(chat.getId());
        }

        // 消息
        ImMessage message = new ImMessage();
        message.setSenderId(userId);
        message.setChatId(messageDTO.getChatId());
        message.setMessageType(messageDTO.getMessageType());
        message.setMessage(messageDTO.getMessage());
        message.setDelFlag(false);
        baseMapper.insert(message);

        // 发给群成员
        List<SysUserVo> groupUserList = groupUserService.listGroupUser(groupId);
        List<ImMessageReceiver> messageReceiverList = new ArrayList<>();
        for (SysUserVo sysUserVo : groupUserList) {
            ImMessageReceiver messageReceiver = new ImMessageReceiver();
            messageReceiver.setMessageId(message.getId());
            messageReceiver.setReceiverId(sysUserVo.getId());
            messageReceiver.setDelFlag(false);
            messageReceiver.setReadFlag(false);
            if (userId.equals(sysUserVo.getId())) {
                messageReceiver.setReadFlag(true);
            }
            messageReceiverList.add(messageReceiver);
        }
        messageReceiverService.saveBatch(messageReceiverList);
        return message;
    }


    @Override
    public List<ImChatMessageBO> listChatUnreadMessage(Long userId, List<Long> chatIdList) {
        return baseMapper.listChatUnreadMessage(userId, chatIdList);
    }

    @Override
    public List<ImMessage> listLatestMessage(Long userId, List<Long> chatIdList) {
        return baseMapper.listLatestMessage(userId, chatIdList);
    }
}
